package com.example.interview.Thread;

import java.util.concurrent.*;

public class ThreadPoolExample {
    public static void main(String[] args) {
        // 核心线程数为 3，最大线程数为 5，空闲线程存活时间为 10 秒
        // 使用 ArrayBlockingQueue 作为工作队列，容量为 10
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3,  // corePoolSize
                5,  // maximumPoolSize
                10, // keepAliveTime
                TimeUnit.SECONDS, // 时间单位
                new ArrayBlockingQueue<>(10) // 工作队列
        );

        // 设置线程工厂，用于创建线程时自定义线程属性
        executor.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName("CustomThread-" + thread.getId());
            return thread;
        });

        // 设置拒绝策略为默认的 AbortPolicy
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        // 提交任务给线程池执行
        for (int i = 0; i < 10; i++) {
            final int taskNumber = i;
            executor.execute(() -> {
                System.out.println("Task " + taskNumber + " executed by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成执行
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                // 如果等待超时，强制关闭线程池
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 处理异常
        }

    }
}
